<template>
  <n-card class="service-node" :bordered="false" :segmented="true">
    <template #header>
      <n-input-group>
        <n-input v-model:value="accessUrl" placeholder="请输入服务接入URL" />
        <n-button type="primary" @click="access">添加</n-button>
      </n-input-group>
    </template>
    <n-grid x-gap="15" :cols="4" :y-gap="15">
      <n-gi v-for="server in servers" :key="server.id">
        <n-card class="server-card" size="small">
          <template #header>
            <div class="title">
              <n-icon-wrapper :size="30" :border-radius="5" icon-color="#fff">
                <n-icon>
                  <database-network-point />
                </n-icon>
              </n-icon-wrapper>
              <span class="text"> {{ server.name }}</span>
            </div>
          </template>
          <template #header-extra>
            <n-icon :size="18" style="cursor: pointer" color="#eb3b5a">
              <delete @click="deleteServerNode(server.id)" />
            </n-icon>
          </template>
          <n-descriptions
            label-align="right"
            label-placement="left"
            :column="1"
            size="small"
            class="server-descriptions"
          >
            <n-descriptions-item label="地址">
              {{ server.proxyServer.host + ":" + server.proxyServer.port }}
            </n-descriptions-item>
            <n-descriptions-item label="延迟">
              <span v-if="server.ping <= 100" style="color: #2ed573">{{ server.ping }}ms</span>
              <span v-else-if="server.ping < 500" style="color: #ffa502">{{ server.ping }}ms</span>
              <span v-else style="color: #ff4757">{{ server.ping }}ms</span>
            </n-descriptions-item>
            <n-descriptions-item label="接入时间">
              {{ moment(server.accessTime).format("yyyy-MM-DD HH:mm:ss") }}
            </n-descriptions-item>
          </n-descriptions>
        </n-card>
      </n-gi>
    </n-grid>
  </n-card>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue"
import { DatabaseNetworkPoint, Delete } from "@icon-park/vue-next"
import {
  doAccess,
  doDeleteServerNode,
  doQueryServerNode,
  type Server
} from "@/api/client/server-management-api"
import moment from "moment"

const accessUrl = ref("")

function access() {
  doAccess(accessUrl.value).then((res) => {
    if (res.data) {
      window.$message.success("接入成功")
      queryServerNode()
    }
  })
}

const servers = ref<Array<Server>>()

function queryServerNode() {
  doQueryServerNode().then((res) => {
    servers.value = res.data
  })
}

function deleteServerNode(id: string) {
  doDeleteServerNode(id).then(() => {
    queryServerNode()
  })
}

onMounted(() => {
  queryServerNode()
})
</script>

<style scoped lang="scss">
@import "index.scss";
</style>
